import java.util.HashMap;
import java.util.Map;

public class question13 {
    public int romanToInt(String s) {
        int countI = 0;
        int countV = 0;
        int countX = 0;
        int countL = 0;
        int countC = 0;
        int countD = 0;
        int countM = 0;

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == 'I') countI++;
            if (ch == 'V') countV++;
            if (ch == 'X') countX++;
            if (ch == 'L') countL++;
            if (ch == 'C') countC++;
            if (ch == 'D') countD++;
            if (ch == 'M') countM++;
        }

        // 先计算所有的加法值
        int iniRes = countI + countV * 5 + countX * 10 + countL * 50 + countC * 100 + countD * 500 + countM * 1000;

        // 再通过遍历，处理所有合法的“减法组合”
        for (int i = 0; i < s.length() - 1; i++) {
            char curr = s.charAt(i);
            char next = s.charAt(i + 1);

            // 如果前一个字符比后一个小，说明是减法组合，要减去两倍的当前值（之前加过一次）
            if (curr == 'I' && (next == 'V' || next == 'X')) {
                iniRes -= 2;
            } else if (curr == 'X' && (next == 'L' || next == 'C')) {
                iniRes -= 20;
            } else if (curr == 'C' && (next == 'D' || next == 'M')) {
                iniRes -= 200;
            }
        }

        return iniRes;
    }

    public int romanToInt2(String s) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int iniRes = 0;

        for (int i = 0; i < s.length() - 1; i++) {
            int curr = map.get(s.charAt(i));
            int next = map.get(s.charAt(i + 1));
            if (curr < next) {
                iniRes -= curr;
            } else {
                iniRes += curr;
            }
        }
        iniRes += map.get(s.charAt(s.length() - 1));
        return iniRes;

    }
}
